<template>
  <div class="agent-container">
    <!-- 搜索栏 -->
    <el-card class="search-container" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="姓名/电话" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <el-button type="primary" :icon="Plus" @click="openDialog('add')">新增经纪人</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>经纪人列表</span>
        </div>
      </template>

      <el-table v-loading="loading" :data="brokerList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="username" label="账号" min-width="120" />
        <el-table-column prop="area" label="负责区域" min-width="150" />
        <el-table-column prop="expertise" label="擅长领域" min-width="150" />
        <el-table-column prop="work_years" label="从业年限" width="100" align="center" />
        <el-table-column label="本月商机" width="100" align="center">
          <template #default="scope">
            {{ scope.row.monthly_leads || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="累计商机" width="100" align="center">
          <template #default="scope">
            {{ scope.row.total_leads || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="operation-btns">
              <el-button type="primary" size="small" @click="openDialog('edit', scope.row)">
                编辑
              </el-button>
              <el-button :type="scope.row.status === 1 ? 'danger' : 'success'" size="small"
                @click="handleStatusChange(scope.row)">
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 经纪人表单 -->
    <el-dialog v-model="dialogVisible" :title="formType === 'add' ? '添加经纪人' : '编辑经纪人'" width="600px" destroy-on-close>
      <el-form ref="brokerFormRef" :model="brokerForm" :rules="formRules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="brokerForm.name" placeholder="请输入经纪人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="brokerForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="brokerForm.id_card" placeholder="请输入身份证号" />
        </el-form-item>
        <template v-if="formType === 'add'">
          <el-form-item label="账号" prop="username">
            <el-input v-model="brokerForm.username" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="brokerForm.password" type="password" placeholder="请输入密码" show-password />
          </el-form-item>
        </template>
        <el-form-item label="负责区域" prop="area">
          <el-input v-model="brokerForm.area" placeholder="请输入负责区域" />
        </el-form-item>
        <el-form-item label="擅长领域" prop="expertise">
          <el-input v-model="brokerForm.expertise" placeholder="请输入擅长领域" />
        </el-form-item>
        <el-form-item label="从业年限" prop="work_years">
          <el-input-number v-model="brokerForm.work_years" :min="0" :max="50" :step="1" style="width: 180px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  getBrokerList,
  createBroker,
  updateBroker,
  updateBrokerStatus
} from '@/api/broker';
import type {
  Broker,
  BrokerCreateRequest,
  BrokerUpdateRequest
} from '@/api/broker';
import { formatDate } from '@/utils/format';

defineOptions({
  name: "Agent"
});

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '启用', value: 1 },
  { label: '禁用', value: 2 }
];

// 表格数据
const loading = ref(false);
const brokerList = ref<Broker[]>([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const formType = ref('add');
const submitLoading = ref(false);
const brokerFormRef = ref<FormInstance>();

// 表单数据
const brokerForm = reactive<BrokerCreateRequest & { id?: number }>({
  name: '',
  phone: '',
  username: '',
  password: '',
  id_card: '',
  area: '',
  expertise: '',
  work_years: 0,
  role_id: undefined,
  partner_id: undefined,
  parent_id: undefined
});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入经纪人姓名', trigger: 'blur' },
    { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchForm.keyword,
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      status: searchForm.status ? Number(searchForm.status) : undefined
    };

    const res = await getBrokerList(params);
    if (res.code === 0) {
      brokerList.value = res.data.list;
      pagination.total = res.data.total;
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取经纪人列表失败', error);
    ElMessage.error('获取经纪人列表失败');
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  return formatDate(new Date(datetime), 'YYYY-MM-DD HH:mm:ss');
};

// 获取状态名称
const getStatusName = (status: number) => {
  return status === 1 ? '启用' : '禁用';
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  return status === 1 ? 'success' : 'danger';
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  handleSearch();
};

// 打开对话框
const openDialog = (type: string, row?: Broker) => {
  formType.value = type;

  // 重置表单
  brokerForm.id = undefined;
  brokerForm.name = '';
  brokerForm.phone = '';
  brokerForm.username = '';
  brokerForm.password = '';
  brokerForm.id_card = '';
  brokerForm.area = '';
  brokerForm.expertise = '';
  brokerForm.work_years = 0;
  brokerForm.role_id = undefined;
  brokerForm.partner_id = undefined;
  brokerForm.parent_id = undefined;

  if (type === 'edit' && row) {
    // 编辑模式，填充数据
    brokerForm.id = row.id;
    brokerForm.name = row.name;
    brokerForm.phone = row.phone;
    brokerForm.id_card = row.id_card;
    brokerForm.area = row.area;
    brokerForm.expertise = row.expertise;
    brokerForm.work_years = row.work_years;
    brokerForm.role_id = row.role_id;
    brokerForm.partner_id = row.partner_id;
    brokerForm.parent_id = row.parent_id;
  }

  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!brokerFormRef.value) return;

  await brokerFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;

      try {
        if (formType.value === 'add') {
          // 创建经纪人
          const createData: BrokerCreateRequest = {
            name: brokerForm.name,
            phone: brokerForm.phone,
            username: brokerForm.username,
            password: brokerForm.password,
            id_card: brokerForm.id_card,
            area: brokerForm.area,
            expertise: brokerForm.expertise,
            work_years: brokerForm.work_years,
            role_id: brokerForm.role_id,
            partner_id: brokerForm.partner_id,
            parent_id: brokerForm.parent_id
          };

          const res = await createBroker(createData);
          if (res.code === 0) {
            ElMessage.success('创建成功');
            dialogVisible.value = false;
            loadData(); // 重新加载数据
          } else {
            ElMessage.error(res.message || '创建失败');
          }
        } else {
          // 更新经纪人
          const updateData: BrokerUpdateRequest = {
            id: brokerForm.id!,
            name: brokerForm.name,
            phone: brokerForm.phone,
            id_card: brokerForm.id_card,
            area: brokerForm.area,
            expertise: brokerForm.expertise,
            work_years: brokerForm.work_years,
            role_id: brokerForm.role_id,
            partner_id: brokerForm.partner_id,
            parent_id: brokerForm.parent_id
          };

          const res = await updateBroker(updateData);
          if (res.code === 0) {
            ElMessage.success('更新成功');
            dialogVisible.value = false;
            loadData(); // 重新加载数据
          } else {
            ElMessage.error(res.message || '更新失败');
          }
        }
      } catch (error) {
        console.error('提交表单失败', error);
        ElMessage.error('操作失败，请稍后重试');
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

// 更改状态
const handleStatusChange = async (row: Broker) => {
  const action = row.status === 1 ? '禁用' : '启用';

  try {
    await ElMessageBox.confirm(`确认要${action}该经纪人吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const newStatus = row.status === 1 ? 2 : 1;
    const res = await updateBrokerStatus({
      id: row.id,
      status: newStatus
    });

    if (res.code === 0) {
      ElMessage.success(`${action}成功`);
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(res.message || `${action}失败`);
    }
  } catch (error) {
    console.log('用户取消操作');
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  loadData();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  loadData();
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.operation-btns {
  display: flex;
  gap: 8px;
  white-space: nowrap;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  color: var(--el-text-color-primary);
  font-weight: 500;
}
</style>